/*!
 @name：layer mobile
 @version: 4.0
 @date: 2022.06.28
 @update:yuguoliang
 @blog: http://www.web000.cn/
 */

;!function (win) {
    var doc = document, query = 'querySelectorAll', claname = 'getElementsByClassName', S = function (s) {
        return doc[query](s);
    };

    //默认配置
    var config = {
        anim: 'scale',  //默认动画类型 up，down，left，right
        fixed: true,
        touchNo: false,
        shade: true,
        shadeClose: true,
        skin: '',
        type: 0,
        zIndex: -1,
    };

    var ready = {
        isObject: function (obj) {
            if (typeof obj === 'object') {
                return Object.prototype.toString.call(obj) === '[object Object]';
            }
            return false;
        },
        extend: function (target, src) {
            if (target === void 0) {
                target = {};
            }
            if (src === void 0) {
                src = {};
            }
            Object.keys(src).forEach(function (key) {
                if (ready.isObject(src[key]) && ready.isObject(target[key]) && Object.keys(src[key]).length > 0) {
                    extend(target[key], src[key]);
                } else {
                    target[key] = src[key];
                }
            });
        },
        touch: function (elem, fn = function () {
        }, en = 'click') {
            elem.addEventListener(en, function (e) {
                fn.call(this, e);
            }, false);
        },
        timer: {},
        end: {}
    };

    var index = 0, classs = ['layui-m-layer'], Layer = function (options) {
        var that = this;
        that.config = JSON.parse(JSON.stringify(config));
        ready.extend(that.config, options);
        console.log(that.config);
        that.view();
    };

    Layer.prototype.view = function () {
        var that = this, config = that.config, layerbox = doc.createElement('div');
        that.id = layerbox.id = classs[0] + index;
        layerbox.setAttribute('class', classs[0] + ' ' + classs[0] + (config.type || 0));
        layerbox.setAttribute('index', index);
        layerbox.setAttribute('anim', config.anim); //增加：动画名称显示
        layerbox.setAttribute('type', config.type || 0); //增加：type类型显示
        if (config.zIndex != -1) {
            layerbox.setAttribute('style', 'z-index:' + config.zIndex); //增加：最外出z-index设置
        }
        if (!config.fixed) {
            layerbox.setAttribute('style', 'position:static;');
        }
        var title = (function () {
            //标题区域
            var titype = typeof config.title === 'object';
            return config.title
                ? '<h3 style="' + (titype ? config.title[1] : '') + '">' + (titype ? config.title[0] : config.title) + '</h3>'
                : '';
        }());
        var button = (function () {
            //按钮区域
            typeof config.btn === 'string' && (config.btn = [config.btn]);
            var btns = (config.btn || []).length, btndom;
            if (btns === 0 || !config.btn) {
                return '';
            }
            btndom = '<span yes type="1">' + config.btn[0] + '</span>'
            if (btns === 2) {
                btndom = '<span no type="0">' + config.btn[1] + '</span>' + btndom;
            }
            return '<div class="layui-m-layerbtn">' + btndom + '</div>';
        }());
        if (!config.fixed) {
            config.style = config.style || '';
        }
        var scrollTopHeight = doc.documentElement.scrollTop || doc.body.scrollTop;
        layerbox.innerHTML = (config.shade ? '<div ' + (typeof config.shade === 'string' ? 'style="' + config.shade + '"' : '') + ' class="layui-m-layershade"></div>' : '')
            + '<div class="layui-m-layermain" ' + (!config.fixed ? 'style="position:absolute;top:' + scrollTopHeight + 'px;"' : '') + '>'
            + '<div class="layui-m-layersection">'
            + '<div class="layui-m-layerchild ' + (config.skin ? 'layui-m-layer-' + config.skin + ' ' : '') + (config.className ? config.className : '') + ' ' + (config.anim ? 'layui-m-anim-' + config.anim : '') + '" ' + (config.style ? 'style="' + config.style + '"' : '') + '>'
            + title
            + '<div class="layui-m-layercont">' + config.content + '</div>'
            + button
            + '</div>'
            + '</div>'
            + '</div>';

        //同type的层不能共存
        var dialogs = doc[claname](classs[0] + config.type), dialen = dialogs.length;
        if (dialen >= 1) {
            layer.close(dialogs[0].getAttribute('index'));
        }

        document.body.appendChild(layerbox);

        that.index = index++;
        var elem = that.elem = S('#' + that.id)[0];
        config.success && config.success(elem, that.index);

        that.action(config, elem);
    };

    Layer.prototype.action = function (config, elem) {
        var that = this;

        //当滑动弹窗内容时，禁止遮罩底部内容一起滑动
        if (config.touchNo) {
            ready.touch(S(".layui-m-layershade")[0], function (e) {
                e.preventDefault();
            }, 'touchmove');
            ready.touch(S(".layui-m-layermain")[0], function (e) {
                e.preventDefault();
            }, 'touchmove');
        }

        //自动关闭
        if (config.time) {
            ready.timer[that.index] = setTimeout(function () {
                layer.close(that.index);
            }, config.time * 1000);
        }

        //确认取消
        var btn = function () {
            var type = this.getAttribute('type');
            if (type == 0) {
                config.no && config.no();
                layer.close(that.index);
            } else {
                config.yes ? config.yes(that.index) : layer.close(that.index);
            }
        };

        if (config.btn) {
            var btns = elem[claname]('layui-m-layerbtn')[0].children, btnlen = btns.length;
            for (var ii = 0; ii < btnlen; ii++) {
                ready.touch(btns[ii], btn);
            }
        }

        //点遮罩关闭
        if (config.shade && config.shadeClose) {
            var shade = elem[claname]('layui-m-layershade')[0];
            ready.touch(shade, function () {
                layer.close(that.index);
            });
        }

        config.end && (ready.end[that.index] = config.end);
    };

    win.layer = {
        v: '4.0',
        index: function () {
            return index;
        },
        open: function (options) {
            //核心方法
            var o = new Layer(options || {});
            return o.index;
        },
        close: function (index, flag) {
            //关闭单独layer层
            //flag参数用于强制关闭多个弹出且，当有一个弹窗为type:3的，这样调用layer.closeAll()就不会一次全部关闭，这个是因为transitionend造成的
            var ibox = S('#' + classs[0] + index)[0];
            if (!ibox) return;
            ibox.innerHTML = '';
            doc.body.removeChild(ibox);
            clearTimeout(ready.timer[index]);
            delete ready.timer[index];
            typeof ready.end[index] === 'function' && ready.end[index]();
            delete ready.end[index];
        },
        closeAll: function (flag) {
            //关闭所有layer层
            var boxs = doc[claname](classs[0]);
            for (var i = 0, len = boxs.length; i < len; i++) {
                layer.close((boxs[0].getAttribute('index') | 0), flag);
            }
        },
        alert : function (param) {
            if (typeof param !== 'string' && typeof param !== 'object') return false;
            let _param = param;
            if (typeof param === 'string') {
                _param = {"msg": param};
            }
            let {
                anim = 'scale',
                btn = ['确定'],
                msg = '',
                title = '',
                skin = 'weui-dialog',
                style = 'width: 80%;max-width: 300px;',
                onOK = function (i) {
                    layer.close(i);
                }
            } = _param;
            let _html = '<div class="' + (skin + '_bd') + '">' + msg + '</div>';
            layer.open({
                anim: anim,
                btn: btn,
                content: _html,
                className: title ? '' : 'title-no',
                style: style,
                skin: skin,
                shadeClose: false,
                title: title,
                touchNo: true,
                yes: onOK
            });
        },
        msg : function (param) {
            if (typeof param !== 'string' && typeof param !== 'object') return false;
            let _param = param;
            if (typeof param === 'string') {
                _param = {"msg": param};
            }
            let {
                anim = 'scale',
                direct = 'middle',
                msg = '操作成功',
                style = '',
                skin = '',
                time = 1.5,
                type = 1,
            } = _param;
            let _html = '', _className = '';
            if (direct === 'middle') {
                _className = 'weui-toast-msg';
                _html = '<span class="weui-tmsg">' + msg + '</span>';
            } else if (direct === 'bottom') {
                _className = 'weui-toast-msg weui-bottom';
                _html = '<span class="weui-tmsg">' + msg + '</span>';
            }
            layer.open({
                anim: anim,
                content: _html,
                className: _className,
                skin: skin,
                shadeClose: false,
                style: style,
                shade: false,
                time: time,
                type: type,
            });
        },
        confirm : function (param) {
            if (typeof param !== 'object') return false;
            let {
                anim = 'scale',
                btn = ['确定', '取消'],
                msg = '',
                title = '',
                skin = 'weui-dialog',
                style = 'width: 80%;max-width: 300px;',
                onOK = function (i) {
                    layer.close(i);
                },
                onCancel = function (i) {
                    layer.close(i);
                }
            } = param;
            let _html = '<div class="' + (skin + '_bd') + '">' + msg + '</div>';
            layer.open({
                anim: anim,
                btn: btn,
                content: _html,
                className: title ? '' : 'title-no',
                style: style,
                skin: skin,
                shadeClose: false,
                title: title,
                touchNo: true,
                yes: onOK,
                no: onCancel
            });
        },
        loading : function (param = {}) {
            if (typeof param !== 'string' && typeof param !== 'object') return false;
            let _param = param;
            if (typeof param === 'string') {
                _param = {"msg": param};
            }
            let {
                anim = 'scale',
                msg = '数据加载中...',
                style = '',
                skin = '',
                type = 0,
            } = _param;
            let _html = '';
            if (skin==='t2'){
                _html += '<span class="van-loading__spinner van-loading__spinner--circular"><svg viewBox="25 25 50 50" class="van-loading__circular"><circle cx="50" cy="50" r="20" fill="none"></circle></svg></span>';
                _html += '<p class="weui-toast__content">' + msg + '</p>';

            }else{
                _html += '<i class="weui-loading weui-icon_toast"></i>';
                _html += '<p class="weui-toast__content">' + msg + '</p>';
            }
            return layer.open({
                anim: anim,
                content: _html,
                className: 'weui-toast',
                style: style,
                skin: skin,
                shadeClose: false,
                shade: 'background-color: rgba(0,0,0,0)',
                type: type,
                touchNo: true,
            });
        },
        toast : function (param) {
            //toast 用于临时显示某些信息，并且会在数秒后自动消失。这些信息通常是轻量级操作的成功、失败或等待状态信息。
            if (typeof param !== 'string' && typeof param !== 'object') return false;
            let _param = param;
            if (typeof param === 'string') {
                _param = {"msg": param};
            }
            let {
                anim = 'scale',
                msg = '操作成功',
                style = 'success',
                skin = '',
                time = 2,
                callback = function () {
                }
            } = _param;

            let _className = '';
            switch (style) {
                case 'success':
                    _className = 'weui-icon-success-no-circle';
                    break;
                case 'error':
                    _className = 'weui-icon-cancel';
                    break;
                default:
                    _className = 'weui-icon-success-no-circle';
                    break;
            }
            let _html = '';
            _html += '<i class="' + _className + ' weui-icon_toast"></i>';
            _html += '<p class="weui-toast__content">' + msg + '</p>';
            layer.open({
                anim: anim,
                className: 'weui-toast',
                content: _html,
                skin: skin,
                shadeClose: false,
                shade: 'background-color: rgba(0,0,0,0)',
                time: time,
                touchNo: true,
                end: function () {
                    callback.call(this);
                }
            });
        }
    };

    'function' == typeof define ? define(function () {
        return layer;
    }) : function () {
        var js = document.scripts, script = js[js.length - 1], jsPath = script.src;
        var path = jsPath.substring(0, jsPath.lastIndexOf("/") + 1);

        //如果合并方式，则需要单独引入layer.css
        if (script.getAttribute('merge')) return;

        document.head.appendChild(function () {
            var link = doc.createElement('link');
            link.href = path + 'need/layer.min.css?v=4.0';
            link.type = 'text/css';
            link.rel = 'styleSheet';
            link.id = 'layermcss';
            return link;
        }());
    }();
}(window);
